package hlhj.fhp.tvlib.utils

import android.os.Build
import android.support.v4.view.MarginLayoutParamsCompat.setMarginEnd
import android.support.v4.view.MarginLayoutParamsCompat.setMarginStart
import android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
import android.support.design.widget.TabLayout
import android.widget.LinearLayout
import android.widget.TextView
import com.liaoinstan.springview.utils.DensityUtil
import java.lang.reflect.AccessibleObject.setAccessible
import java.lang.reflect.Field


/**
 * Created by Never Fear   on 2018\9\6 0006.
Never More....
 */
object TabUtils {

    fun setTabWidth(tabLayout: TabLayout, padding: Int) {
        tabLayout.post {
            try {
                //拿到tabLayout的mTabStrip属性
                val mTabStrip = tabLayout.getChildAt(0) as LinearLayout



                for (i in 0 until mTabStrip.childCount) {
                    val tabView = mTabStrip.getChildAt(i)

                    //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                    val mTextViewField = tabView.javaClass.getDeclaredField("mTextView")
                    mTextViewField.setAccessible(true)

                    val mTextView = mTextViewField.get(tabView) as TextView

                    tabView.setPadding(0, 0, 0, 0)

                    //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                    var width = 0
                    width = mTextView.getWidth()
                    if (width == 0) {
                        mTextView.measure(0, 0)
                        width = mTextView.getMeasuredWidth()
                    }

                    //设置tab左右间距 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                    val params = tabView.layoutParams as LinearLayout.LayoutParams
                    params.width = width
                    params.leftMargin = padding
                    params.rightMargin = padding
                    tabView.layoutParams = params

                    tabView.invalidate()
                }

            } catch (e: NoSuchFieldException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            }
        }

    }


}